package pl.koziolekweb.szkola.EFRegExNames;

// EF-RegExNames/RegEx.java
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;


/*  Program czyta plik input.txt i wybiera z niego imiona
 *  (napisy rozpoczynajace sie od duzej litery, potem male).
 *  Nastepnie drukuje liste imion wraz z liczba wystapien i
 *  lista numerow linii gdzie dane imie wystapilo. Korzysta
 *  z klasy Name. Czyta plik tekstowy "input.txt" (UTF-8).
 */
public class RegEx {

    private HashMap<String,Name> map;

    public static void main(String[] args) {
        new RegEx("input.txt");
    }

    public RegEx(String filename) {
        File input = new File(filename);
        BufferedReader br = null;
        map = new HashMap<String,Name>();
        if (!input.canRead() || !input.canRead()) {
            System.err.println("File inaccessible");
            System.exit(1);
        }

        try {
            br = new BufferedReader(
                    new InputStreamReader(
                    new FileInputStream(input),"UTF-8"));

            String line, name,
                   patt = "\\b\\p{Lu}\\p{Ll}+\\b";
            Pattern pattern = null;
            try {
                pattern = Pattern.compile(patt);
            } catch(PatternSyntaxException e) {
                System.err.println("Wrong pattern");
                System.exit(1);
            }
            Matcher matcher = pattern.matcher("");

            int lineNo = 0;
            while ((line = br.readLine()) != null) {
                lineNo++;
                matcher.reset(line);
                if (matcher.find()) {
                    do {
                        name = matcher.group();
                        if (!map.containsKey(name))
                            map.put(name,
                                    new Name(name,lineNo));
                        else
                            map.get(name).addNum(lineNo);
                    } while (matcher.find());
                }
            }
        } catch(IOException e) {
            System.err.println("Something wrong - exiting");
            System.exit(1);
        }
        finally {
            try { if (br != null) br.close(); }
            catch(IOException ignored) {}
        }

        for (String n : map.keySet())
            System.out.println(map.get(n));
    }
}